﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication2
{
    public partial class Login : System.Web.UI.Page
    {
        public string cookieHost = ConfigHelper.CookieHost;
        protected void Page_Load(object sender, EventArgs e)
        {
            string localhost = string.Format("http://{0}:{1}/", Request.Url.Host, Request.Url.Port);
            string checkOnline = Request.QueryString.Get("CheckOnline");
            //如果用户已经检测过是否在线了，并且确认没有登录sso
            if (!string.IsNullOrWhiteSpace(checkOnline) && checkOnline == "true")
            {
                //走正常的登录流程，获取用户提交的用户名和密码之后，调用sso接口去验证
            }
            //调用sso站点的iframe,去验证是否在主站有会话
            else
            {
                string loginUrl = string.Format("loginUrl={0}login", localhost);
                string returnUrl = string.Format("returnUrl={0}loginsuccess", localhost);
                string appKey = string.Format("appKey={0}", ConfigHelper.AppKey);
                string iframeUrl = ConfigHelper.CookieHost + "?";
                string url = string.Format("{0}{1}&{2}&{3}", iframeUrl, returnUrl, loginUrl, appKey);
                string scriptBlock = string.Format(@"jQuery('#sso').attr('src','{0}')", url);
                string script = "jQuery(function(){" + scriptBlock + "})";
                ClientScript.RegisterStartupScript(this.GetType(), "iframe", script, true);
            }
        }
        //loginin
        protected void login_Click(object sender, EventArgs e)
        {
            string localhost = string.Format("http://{0}:{1}/", Request.Url.Host, Request.Url.Port);
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(ConfigHelper.APIHost);
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("appliation/json"));
            UserInfo user = new UserInfo()
            {
                AppKey = ConfigHelper.AppKey,
                AppSecret = ConfigHelper.AppSecret,
                UserName = ConfigHelper.UserName,
                Password = ConfigHelper.Password,
                Ip = Request.UserHostAddress,
                ForceLogin = 0,
            };
            HttpResponseMessage response = client.PostAsJsonAsync("api/sso/login", user).Result;
            if (response.IsSuccessStatusCode)
            {
                var result = response.Content.ReadAsAsync<Result>().Result;
                //如果登录成功
                if (result.Code == 0)
                {
                    //往cookieHost写cookie
                    string strAnd = "&";
                    string returnUrlValue = Server.HtmlEncode($@"{localhost}loginsuccess{strAnd}token={result.Data?.Token}{strAnd}userid={ result.Data?.UserID}{strAnd}appkey={ConfigHelper.AppKey}");
                    string returnUrl = string.Format("returnUrl={0}", returnUrlValue);
                    string token = string.Format("token={0}", result.Data.Token);
                    string userId = string.Format("userId={0}", result.Data.UserID);
                    string iframeUrl = ConfigHelper.CookieHost + "?";
                    string url = string.Format("{0}{1}&{2}&{3}&{4}", iframeUrl, returnUrl, token, userId, ConfigHelper.AppKey);
                    string scriptBlock = string.Format(@"jQuery('#sso').attr('src','{0}')", url);
                    string script = "jQuery(function(){" + scriptBlock + "})";
                    ClientScript.RegisterStartupScript(this.GetType(), "iframe", script, true);
                }
                else
                {
                    Response.Write(string.Format("<script>alert('{0}')</script>", result.Message));
                }
            }
        }

        protected void forcelogin_Click(object sender, EventArgs e)
        {
            string localhost = string.Format("http://{0}:{1}/", Request.Url.Host, Request.Url.Port);
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(ConfigHelper.APIHost);
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("appliation/json"));
            UserInfo user = new UserInfo()
            {
                AppKey = ConfigHelper.AppKey,
                AppSecret = ConfigHelper.AppSecret,
                UserName = "km",
                Password = "123456",
                Ip = Request.UserHostAddress,
                ForceLogin = 1,
            };
            HttpResponseMessage response = client.PostAsJsonAsync("api/sso/login", user).Result;
            if (response.IsSuccessStatusCode)
            {
                var result = response.Content.ReadAsAsync<Result>().Result;
                //如果登录成功
                if (result.Code == 0)
                {
                    //往cookieHost写cookie
                    string returnUrlValue = Server.HtmlEncode(string.Format("{0}loginsuccess?token={1}&userid={2}&appkey={3}", localhost, result.Data?.Token, result.Data?.UserID, ConfigHelper.AppKey));
                    string returnUrl = string.Format("returnUrl={0}", returnUrlValue);
                    string token = string.Format("token={0}", result.Data.Token);
                    string userId = string.Format("userId={0}", result.Data.UserID);
                    string iframeUrl = ConfigHelper.CookieHost + "?";
                    string url = string.Format("{0}{1}&{2}&{3}&{4}", iframeUrl, returnUrl, token, userId, ConfigHelper.AppKey);
                    string scriptBlock = string.Format(@"jQuery('#sso').attr('src','{0}')", url);
                    string script = "jQuery(function(){" + scriptBlock + "})";
                    ClientScript.RegisterStartupScript(this.GetType(), "iframe", script, true);
                }
                else
                {
                    Response.Write(string.Format("<script>alert('{0}')</script>", result.Message));
                }
            }
        }
    }
}